package com.yssoft.service.core;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yssoft.datasource.DataSource;
import com.yssoft.datasource.DataSourceContextHolder;
import com.yssoft.entity.FileUpload;
import com.yssoft.entity.core.*;
import com.yssoft.mapper.core.TEnterpriseLicenceMapper;
import com.yssoft.mapper.core.TEnterpriseMapper;
import com.yssoft.shiro.MyRealm;
import com.yssoft.utils.*;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 陈翼东
 * @time 2018/4/25 下午 05:52
 * @ 企业管理service
 */
@Service
@DataSource(DataSourceContextHolder.MYSQL)
public class EnterpriseService {

    private static Logger logger = Logger.getLogger(EnterpriseService.class);

    @Resource
    private TEnterpriseMapper enterpriseMapper;
    @Resource
    private TEnterpriseLicenceMapper enterpriseLicenceMapper;
    @Autowired
    private CompanyServe companyServe;
    @Resource
    private FileUploadService fileUploadService;

    /**
     * 分页查询企业信息
     *
     * @param pageNumber   当前页数
     * @param pageSize     页面显示数据条数
     * @param name         企业名称
     * @param abbreviation 企业简称
     * @param legalPerson  法人
     * @param contact      联系人
     * @param productStat  生产状态
     * @param approvalStat 审核状态
     * @return
     */
    public JSONObject queryEnterprisePage(int pageNumber, int pageSize, String name, String abbreviation, String legalPerson, String contact, String productStat, String approvalStat) {
        Integer entId = UserHelper.getCurrentCompanyId();
        PageHelper.startPage(pageNumber, pageSize);//下面第一个查询结果进行分页
        Map<String, Object> param = new HashMap<>();
        Integer accId = UserHelper.getCurrentUser().getId();
        Integer isSystem = enterpriseMapper.queryRoleIdByAccId(accId);
        if (isSystem > 0) {
            param.put("isSystem", 1);
        }
        param.put("companyId", entId);
        param.put("name", name);
        param.put("abbreviation", abbreviation);
        param.put("legalPerson", legalPerson);
        param.put("contact", contact);
        param.put("product_stat", productStat);
        param.put("approval_stat", approvalStat);
        List<Map<String, Object>> personList = enterpriseMapper.selectAllSql(param);
        int count = enterpriseMapper.selectCountSql(param);//查询条数
        List<Map<String, Object>> mapList = queryCompanyList(personList);
        JSONObject jsonObject = LayuiUtil.getJSONObjectByMap(mapList, count, "", "");
        return jsonObject;
    }

    private List<Map<String, Object>> queryCompanyList(List<Map<String, Object>> list) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                Map<String, Object> comMap = new HashMap<>();
                TcCompany company = companyServe.queryCompanyInfoByLicense(map.get("sc").toString());
                comMap.put("id", map.get("id"));
                comMap.put("name", company.getCompanyName());
                comMap.put("product_address", company.getAddress());
                comMap.put("legal_person", company.getLegalPerson());
                comMap.put("contact", company.getContact());
                comMap.put("companyTypeName", company.getCompanyTypeName());
                comMap.put("phone", company.getContactPhone());
                comMap.put("license", company.getLicense());
                comMap.put("creditCode", company.getCreditCode());
                comMap.put("address", company.getAddress());
                comMap.put("deptName", company.getDeptName());
                comMap.put("manageStatus", company.getManageStatus().equals("1") ? "是" : "否");
                comMap.put("licence_code", map.get("licence_code"));
                mapList.add(comMap);
            }
        }
        return mapList;
    }

    /**
     * 分页查询所有企业信息
     *
     * @param pageNumber 当前页数
     * @param pageSize   页面显示数据条数
     * @param name       企业名称
     * @return
     */
    public JSONObject queryEnterpriseAllPage(int pageNumber, int pageSize, String name, String companyIds) {
        PageHelper.startPage(pageNumber, pageSize);//下面第一个查询结果进行分页
        Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        List<Map<String, Object>> personList = enterpriseMapper.selectAllNoCompany(param);
        String[] companyArr = companyIds.split(",");
        List<String> list = new ArrayList<>();
        Collections.addAll(list, companyArr);
        for (Map<String, Object> stringObjectMap : personList) {
            if (list.contains(stringObjectMap.get("id") + "")) {
                stringObjectMap.put("LAY_CHECKED", true);
            }
        }
        int count = enterpriseMapper.selectAllNoCompanyCount(param);//查询条数
        JSONObject jsonObject = LayuiUtil.getJSONObjectByMap(personList, count, "", "");
        return jsonObject;
    }

    /**
     * 根据企业id查询企业信息
     *
     * @param enterpriseId 企业的id
     * @return 企业实体
     */
    public TEnterprise queryEnterpriseById(Object enterpriseId) {
        try {
            return enterpriseMapper.selectByPrimaryKey(enterpriseId);
        } catch (Exception e) {
            logger.error("com.yssoft.service.core.EnterpriseService.queryEnterpriseById根据企业id查询企业信息报错：" + e.getMessage());
            return null;
        }
    }

    /**
     * 根据企业实体查询企业信息（可以使用实体中多个条件）
     *
     * @param enterprise 企业的对象
     * @return 企业实体
     */
    public TEnterprise queryEnterpriseByEntity(TEnterprise enterprise) {
        try {
            return enterpriseMapper.selectOne(enterprise);
        } catch (Exception e) {
            logger.error("com.yssoft.service.core.EnterpriseService.queryEnterpriseByEntity根据企业对象查询企业信息报错：" + e.getMessage());
            return null;
        }
    }

    /**
     * 添加企业对象
     *
     * @param enterprise         企业实体，添加的内容应使用set方法将值设置完
     * @param tEnterpriseLicence
     * @return 返回0则失败，返回大于0的数表示成功
     */
    @Transactional(rollbackFor = Exception.class)
    public int addEnterprise(TEnterprise enterprise, String proclaIds, TenterpriseLicence2 tEnterpriseLicence) {
        try {
            /*企业信息实体补充基础数据*/
            enterprise.setApprovalStat("1");
            enterprise.setCreateTime(new Date());
            MyRealm.ShiroUser user = UserHelper.getCurrentUser();
            enterprise.setCreatorName(user.getName());
            /*enterprise.setDeptName(user.getDept_name());
            enterprise.setDeptId(user.getDept_id());*/
            enterprise.setCreatorId(user.getId());
            enterprise.setDeleteFlag("0");
            /*保存企业信息*/
            enterpriseMapper.insertGetById(enterprise);
            /*获取新增企业信息id*/
            Integer id = enterprise.getId();
            /*添加企业与生产范围中间表数据*/
            if (proclaIds != null && !"".equals(proclaIds)) {
                String[] procalid = proclaIds.split(",");
                for (int i = 0; i < procalid.length; i++) {
                    enterpriseMapper.insertEntProCla(id, Integer.parseInt(procalid[i]));
                }
            }
            /*企业证照基础信息*/
            TEnterpriseLicence licence = new TEnterpriseLicence();
            licence.setTEId(id);
            licence.setDeleteFlag("0");
            licence.setCreateTime(new Date());
            licence.setCreatorName(user.getName());
            licence.setCreatorId(user.getId());
            /*licence.setDeptId(user.getDept_id());
            licence.setDeptName(user.getDept_name());*/
            /*保存企业证照信息1*/
            licence.setLicenceCode(tEnterpriseLicence.getLicenceCode());
            licence.setLicenceImg(tEnterpriseLicence.getLicenceImg());
            licence.setLicenceTimg(tEnterpriseLicence.getLicenceTimg());
            licence.setGrantDate(tEnterpriseLicence.getGrantDate());
            licence.setInvalidDate(tEnterpriseLicence.getInvalidDate());
            licence.setType(tEnterpriseLicence.getLicenceType());
            licence.setDescribed(tEnterpriseLicence.getDescribed());
            enterpriseLicenceMapper.insert(licence);
            /*保存企业证照信息2*/
            licence.setLicenceCode(tEnterpriseLicence.getLicenceCode2());
            licence.setLicenceImg(tEnterpriseLicence.getLicenceImg2());
            licence.setLicenceTimg(tEnterpriseLicence.getLicenceTimg2());
            licence.setGrantDate(tEnterpriseLicence.getGrantDate2());
            licence.setInvalidDate(tEnterpriseLicence.getInvalidDate2());
            licence.setType(tEnterpriseLicence.getLicenceType2());
            licence.setDescribed(tEnterpriseLicence.getDescribed2());
            enterpriseLicenceMapper.insert(licence);
            return id;
        } catch (Exception e) {
            logger.error("com.yssoft.service.core.EnterpriseService.addEnterprise添加企业报错：" + e.getMessage());
            return 0;
        }
    }

    /**
     * 使用企业的id删除企业信息
     *
     * @param entityId 企业的id
     * @return 返回0则失败，返回大于0的数表示成功
     */
    @Transactional(rollbackFor = Exception.class)
    public int delEnterprise(Object entityId) {
        try {
            TEnterprise ent = enterpriseMapper.selectByPrimaryKey(entityId);
            ent.setDeleteFlag("1");
            return enterpriseMapper.updateByPrimaryKeySelective(ent);
        } catch (Exception e) {
            logger.error("com.yssoft.service.core.EnterpriseService.delEnterprise删除企业报错：" + e.getMessage());
            return 0;
        }

    }

    /**
     * 多个条件删除企业信息
     *
     * @param enterprise 企业的实体
     * @return 返回0则添加失败，返回大于0的数表示添加成功
     */
    @Transactional(rollbackFor = Exception.class)
    public int delEnterprise(TEnterprise enterprise) {
        try {
            return enterpriseMapper.delete(enterprise);
        } catch (Exception e) {
            logger.error("com.yssoft.service.core.EnterpriseService.delEnterprise删除企业报错：" + e.getMessage());
            return 0;
        }
    }

    /**
     * @param enterprise
     * @param licenseImgFile
     * @param businessLicenseImgFile
     * @return
     */
    public boolean updateCompany(TEnterprise enterprise, MultipartFile licenseImgFile, MultipartFile businessLicenseImgFile) {
        if (licenseImgFile != null && !licenseImgFile.isEmpty()) {
            //调用监管端请求接口，上传许可证照片
            FileUpload fileUpload = fileUploadService.uploadFile(licenseImgFile);
            enterprise.setLicenseFile(fileUpload.getFilePath());
            enterprise.setLicenseFileId(fileUpload.getId());
        }
        //获取营业执照照片地址
        if (businessLicenseImgFile != null && !businessLicenseImgFile.isEmpty()) {
            //调用监管端请求接口，上传营业执照
            FileUpload fileUpload = fileUploadService.uploadFile(businessLicenseImgFile);
            enterprise.setBusinessLicenseFile(fileUpload.getFilePath());
            enterprise.setBusinessLicenseFileId(fileUpload.getId());
        }
        return companyServe.updateCompany(enterprise);

    }

    /**
     * 根据企业实体修改企业信息(id不能为空)
     *
     * @param enterprise
     * @return 返回0则失败，返回大于0的数表示成功
     */
    @Transactional(rollbackFor = Exception.class)
    public int editEnterprise(TEnterprise enterprise, String proclaIds, MultipartFile file, MultipartFile licenseImgFile, MultipartFile businessLicenseImgFile) {
        /*删除中间表数据*/
        enterpriseMapper.deleteEntByProById(enterprise.getId());
        /*修改中间表数据*/
        if (proclaIds != null && !"".equals(proclaIds)) {
            String[] procalid = proclaIds.split(",");
            for (int i = 0; i < procalid.length; i++) {
                enterpriseMapper.insertEntProCla(enterprise.getId(), Integer.parseInt(procalid[i]));
            }
        }

        //获取许可证照片地址
        if (licenseImgFile != null && !licenseImgFile.isEmpty()) {
            //保存许可证信息
            String licenseImg = UploadFile.processUploadedVideo(licenseImgFile);
            String filename = licenseImgFile.getOriginalFilename();
            enterprise.setLicenseImg(filename);
            addEnterpriseLicence(enterprise, licenseImg, filename, "1");
        }  //获取营业执照照片地址
        if (businessLicenseImgFile != null && !businessLicenseImgFile.isEmpty()) {
            //保存许可证信息
            String licenseImg = UploadFile.processUploadedVideo(businessLicenseImgFile);
            String filename = businessLicenseImgFile.getOriginalFilename();
            enterprise.setPicImg(filename);
            addEnterpriseLicence(enterprise, licenseImg, filename, "2");
        }
        if (file != null && !file.isEmpty()) {
            String changeMaterials = UploadFile.processUploadedVideo(file);
            if (changeMaterials != null && !changeMaterials.isEmpty()) {
                String filename = file.getOriginalFilename();
                enterprise.setChangeMaterialName(filename);
                enterprise.setChangeMaterials(changeMaterials);
            } else {
                logger.error("[变更材料上传] 文件上传失败，返回值为空，保持原有的changeMaterials值");
                // 文件上传失败，保持原值（从数据库查询）
                // 需要从数据库重新查询原值，因为enterprise对象可能已经被表单数据覆盖
                TEnterprise originalEnterprise = enterpriseMapper.selectByPrimaryKey(enterprise.getId());
                if (originalEnterprise != null && originalEnterprise.getChangeMaterials() != null) {
                    enterprise.setChangeMaterials(originalEnterprise.getChangeMaterials());
                }
            }
        }
        //保存信息变更
        CompanyModifyUtil.companyModify(enterprise, enterprise.getChangeMaterials(), "1", "主体变更", Long.parseLong(enterprise.getId().toString()));
        int result = enterpriseMapper.updateByPrimaryKeySelective(enterprise);
        return result;
    }

    /**
     * 保存企业证件信息
     *
     * @param enterprise
     * @param licenceImg
     * @param licenceImgName
     */
    private void addEnterpriseLicence(TEnterprise enterprise, String licenceImg, String licenceImgName, String type) {
        //删除企业许可证信息
        enterpriseLicenceMapper.deleteLicenceInfo(enterprise.getId(), type);
        TEnterpriseLicence enterpriseLicence = new TEnterpriseLicence();
        enterpriseLicence.setTEId(enterprise.getId());
        enterpriseLicence.setType(type);
        enterpriseLicence.setLicenceImg(licenceImg);
        enterpriseLicence.setLicenceImgName(licenceImgName);
        if (type.equals("1")) {
            enterpriseLicence.setName("许可证照片");
            enterpriseLicence.setGrantDate(enterprise.getGrantDate());
            enterpriseLicence.setInvalidDate(enterprise.getInvalidDate());
        } else {
            enterpriseLicence.setName("营业执照");
            enterpriseLicence.setGrantDate(enterprise.getIssueDate());
            enterpriseLicence.setInvalidDate(enterprise.getExpireDate());
        }
        enterpriseLicenceMapper.insert(enterpriseLicence);
    }

    public TEnterpriseLicence queryLicenceByCode(Integer enterpriseId, String type) {
        return enterpriseLicenceMapper.queryLicenceInfo(enterpriseId, type);

    }

    /**
     * APP 修改企业信息
     *
     * @param licenceTimg
     * @param licenceImg
     * @param enterprise
     * @author 王永宁
     */
    @Transactional
    public String updeteEnterprise(TEnterprise enterprise, String licenceImg, String licenceTimg) {
        String msg = "";
        try {
            enterpriseMapper.updateByPrimaryKeySelective(enterprise);
            TEnterpriseLicence ent = new TEnterpriseLicence();
            ent.setType("2");
            ent.setTEId(enterprise.getId());
            TEnterpriseLicence ent1 = enterpriseLicenceMapper.selectOne(ent);
            if (null != ent1) {
                ent1.setLicenceImg(licenceImg);
                ent1.setLicenceTimg(licenceTimg);
                enterpriseLicenceMapper.updateByPrimaryKeySelective(ent1);
            } else {
                ent.setLicenceImg(licenceImg);
                ent.setLicenceTimg(licenceTimg);
                enterpriseLicenceMapper.insertSelective(ent);
            }
            msg = "保存成功";
        } catch (Exception e) {
            msg = "保存失败";
        }
        return msg;

    }

    /**
     * APP获取企业图片
     *
     * @param id
     * @return
     */
    public TEnterpriseLicence queryLicenceByEId(Integer id) {
        TEnterpriseLicence ent = new TEnterpriseLicence();
        ent.setTEId(id);
        ent.setType("2");
        return enterpriseLicenceMapper.selectOne(ent);
    }

    public String queryRolePermissions() {
        Integer userId = UserHelper.getCurrentUserId();
        Map<String, Object> role = enterpriseMapper.queryRolePermissions(userId);
        if (role != null) {
            return role.get("data_permissions").toString();
        } else {
            return null;
        }
    }

    public Integer queryRoleIdByAccId() {
        Integer accId = UserHelper.getCurrentUser().getId();
        Integer isSystem = enterpriseMapper.queryRoleIdByAccId(accId);
        return isSystem;
    }

    /**
     * 企业证照预警查询列表
     * 王永宁
     *
     * @param page
     * @param limit
     * @param yy
     * @param sc
     * @return
     */
    public JSONObject queryWarningEnterprisePage(int page, int limit, String yy, String sc) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //制定日期格式
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        String validityDate = df.format(c.getTime());
        PageHelper.startPage(page, limit);//下面第一个查询结果进行分页
        Map<String, Object> param = new HashMap<>();
        if (yy != null && yy != "") {
            switch (yy) {
                case "1":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 1);
                    validityDate = df.format(c.getTime());
                    param.put("yy", validityDate);
                    break;
                case "2":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 2);
                    validityDate = df.format(c.getTime());
                    param.put("yy", validityDate);
                    break;
                case "3":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 3);
                    validityDate = df.format(c.getTime());
                    param.put("yy", validityDate);
                    break;
                case "4":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 4);
                    validityDate = df.format(c.getTime());
                    param.put("yy", validityDate);
                    break;
                case "5":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 5);
                    validityDate = df.format(c.getTime());
                    param.put("yy", validityDate);
                    break;
                case "6":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 6);
                    validityDate = df.format(c.getTime());
                    param.put("yy", validityDate);
                    break;
            }
        }
        if (sc != null && sc != "") {
            switch (sc) {
                case "1":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 1);
                    validityDate = df.format(c.getTime());
                    param.put("sc", validityDate);
                    break;
                case "2":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 2);
                    validityDate = df.format(c.getTime());
                    param.put("sc", validityDate);
                    break;
                case "3":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 3);
                    validityDate = df.format(c.getTime());
                    param.put("sc", validityDate);
                    break;
                case "4":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 4);
                    validityDate = df.format(c.getTime());
                    param.put("sc", validityDate);
                    break;
                case "5":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 5);
                    validityDate = df.format(c.getTime());
                    param.put("sc", validityDate);
                    break;
                case "6":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 6);
                    validityDate = df.format(c.getTime());
                    param.put("sc", validityDate);
                    break;
            }
        }
        List<Map<String, Object>> list = enterpriseMapper.selectAllSqlForWarning(param);
        for (Map<String, Object> map : list) {
            if (map.get("yyDate") != null && map.get("yyDate") != "") {
                int res = map.get("yyDate").toString().compareTo(df.format(new Date()));
                if (res >= 0) {
                    map.put("yyguoqi", "0");
                } else {
                    map.put("yyguoqi", "1");
                }

            }
            if (map.get("scDate") != null && map.get("scDate") != "") {
                int res = map.get("scDate").toString().compareTo(df.format(new Date()));
                if (res >= 0) {
                    map.put("scguoqi", "0");
                } else {
                    map.put("scguoqi", "1");
                }

            }

        }
        int count = enterpriseMapper.selectCountSqlForWarning(param);//查询条数
        JSONObject jsonObject = LayuiUtil.getJSONObjectByMap(list, count, "", "");
        return jsonObject;
    }

    /**
     * @方法名: selectAll
     * @创建人: 陈翼东
     * @时间: 2018/6/14 9:39
     * @参数: [childrenList]
     * @返回值: java.util.List<com.yssoft.entity.core.TEnterprise>
     * @说明: 查询在这个地区中的企业信息
     */
    public List<TEnterprise> selectAll(String areaId) {
        return enterpriseMapper.selectAllByArea(areaId);
    }

    public JSONObject selectAllPage(int pageNumber, int pageSize, String areaId, String name) {

        //获取当前登陆账号信息

        PageHelper.startPage(pageNumber, pageSize);//下面第一个查询结果进行分页
        HashMap<String, Object> param = new HashMap<>();
        param.put("areaId", areaId);
        param.put("pageStart", pageNumber * pageSize);
        param.put("pageSize", pageSize);
        param.put("companyName", name);


        List<TEnterprise> TEnterpriseList = enterpriseMapper.selectAllByPage(param);

        int count = enterpriseMapper.selectAllByPageCount(param).size();

        JSONObject jsonObject = null;
        try {
            jsonObject = LayuiUtil.getJSONObjectByObject(TEnterpriseList, count, "", "0");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            LayuiUtil.getJSONObjectByMap(null, count, "查询失败", "1");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            LayuiUtil.getJSONObjectByMap(null, count, "查询失败", "1");
        }
        return jsonObject;

    }
}
